package org.example.java.util.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * static synchronized 保证类同步
 * synchronized 实例同步
 * User: ZhangJuntao
 * Date: 13-12-17
 * Time: 上午7:52
 */
public class SynchronizedTest {
  protected static synchronized void doSome() throws InterruptedException {
    Long flag = System.nanoTime();
    System.out.printf("\nstart %s .%n ", flag);
    TimeUnit.MILLISECONDS.sleep(100);
    System.out.println("so some thing.");
    System.out.println("end " + flag);
  }

  protected  void doSomethingElse() throws InterruptedException {
    synchronized (this) {
      Long flag = System.nanoTime();
      System.out.printf("start %s .%n ", flag);
      TimeUnit.MILLISECONDS.sleep(100);
      System.out.println("so some thing else.");
      System.out.println("end " + flag);
    }
  }

  protected void doSomethingElse2() throws InterruptedException {
    synchronized (this) {
      Long flag = System.nanoTime();
      System.out.printf("start2 %s .%n ", flag);
      TimeUnit.MILLISECONDS.sleep(500);
      System.out.println("so some thing else2.");
      System.out.println("end2 " + flag);
    }
  }

  public static void main(String[] args) throws Exception {
    int i = 5;
    ExecutorService executor = Executors.newCachedThreadPool();
    final SynchronizedTest t = new SynchronizedTest();
    while (i-- > 0) {
      executor.execute(new Runnable() {
        @Override
        public void run() {
          try {
//            SynchronizedTest.doSome();
            t.doSomethingElse();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      });
      executor.execute(new Runnable() {
        @Override
        public void run() {
          try {
            t.doSomethingElse2();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      });
    }
    executor.shutdown();
  }
}
